<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import type { VbenFormProps } from '#/adapter/form';
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { OAuth2Client } from '#/api/platform/client';

import { Page, useVbenModal } from '@vben/common-ui';
import { Plus } from '@vben/icons';

import { ElButton, ElLoading, ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { changeStatus, delClient, listClient } from '#/api/platform/client';
import { $t } from '#/locales';

import Form from './component/form.vue';
import { columnsSchema, querySchema } from './data';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

/**
 * 编辑系统用户
 * @param row
 */
async function onEdit(row: OAuth2Client) {
  formModalApi.setData(row).open();
}

/**
 * 创建新系统用户
 */
function onCreate() {
  formModalApi.setData(null).open();
}

/**
 * 删除系统用户
 * @param row
 */
function onDelete(row: OAuth2Client) {
  const loading = ElLoading.service({
    lock: true,
    text: $t('ui.actionMessage.deleting', [row.clientName]),
  });
  delClient(row.id)
    .then(() => {
      successCallback();
    })
    .finally(() => {
      loading.close();
    });
}

/**
 * 表格操作按钮的回调函数
 */
function onActionClick({ code, row }: OnActionClickParams<OAuth2Client>) {
  switch (code) {
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
  }
}

const formOptions: VbenFormProps = {
  collapsed: true, // 默认展开
  schema: querySchema(), // 查询参数
  showCollapseButton: false, // 控制表单是否显示折叠按钮
  submitOnEnter: false, // 按下回车时是否提交表单
};

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridEvents: {},
  gridOptions: {
    columns: columnsSchema(onStatusChange, onActionClick),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await listClient({
            pageNum: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      search: true,
    },
    treeConfig: {
      transform: false,
    },
  } as VxeTableGridOptions,
});

/**
 * 状态开关即将改变
 * @param newStatus 期望改变的状态值
 * @param row 行数据
 * @returns 返回false则中止改变，返回其他值（undefined、true）则允许改变
 */
async function onStatusChange(newStatus: string, row: OAuth2Client) {
  const status: Recordable<string> = {
    '1': '禁用',
    '0': '启用',
  };
  return ElMessageBox.confirm(
    `是否将状态切换为 【${status[newStatus.toString()]}】 吗？`,
    `切换状态`,
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(async () => {
      await changeStatus(row.id, newStatus);
      return true;
    })
    .catch(() => {
      return false;
    });
}

/**
 * 成功回调
 */
function successCallback() {
  gridApi.query();
  ElMessage.success($t('ui.actionMessage.operationSuccess'));
}
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="successCallback" />
    <Grid>
      <template #toolbar-tools>
        <ElButton
          type="primary"
          @click="onCreate"
          v-access:code="['oauth2_client:add']"
        >
          <Plus class="size-5" />
          {{ $t('ui.actionTitle.create', [$t('client.client')]) }}
        </ElButton>
      </template>
    </Grid>
  </Page>
</template>
